/*
 ******************************** 
 */
package BandB.Tool.GPhoneManager.FileExplorer;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import android.content.Context;
import android.os.Process;

/**
 * 
 * @author gjbie
 * 
 */
public final class FileLauncher {

	private List<FileItem> mFiles;
	private static FileLauncher s_mInstance;

	// private static Context mContext;

	private FileLauncher() {

	}

	/**
	 * constructor for this class
	 * 
	 * @param context
	 * @return
	 */
	public static FileLauncher getInstance(final Context context) {
		if (null == s_mInstance) {
			s_mInstance = new FileLauncher();
		}
		// uninstallUtil = new UninstallUtil(context);
		// mContext = context;
		return s_mInstance;
	}

	private class FilesLoader implements Runnable {
		private final WeakReference<FileExplorer> mLauncher;

		private volatile boolean mStopped;
		private volatile boolean mRunning;

		private File mRoot;
		private String mKeyword;

		FilesLoader(FileExplorer fileExplorer, File root, String keyword) {
			mLauncher = new WeakReference<FileExplorer>(fileExplorer);
			mRoot = root;
			mKeyword = keyword;
		}

		void stop() {
			mStopped = true;
		}

		boolean isRunning() {
			return mRunning;
		}

		public void run() {
			mRunning = true;

			android.os.Process
					.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

			final FileExplorer launcher = mLauncher.get();
			final FileAdapter fileAdapter = mFileAdapter;
			ChangeNotifier action = new ChangeNotifier(fileAdapter, true);

			LinkedList<File> list = new LinkedList<File>();
			File file[] = mRoot.listFiles();
			for (int i = 0; i < file.length; i++) {
				if (file[i].isDirectory()) {
					list.add(file[i]);
				}
				if (file[i].getName().contains(mKeyword.toLowerCase())) {
					FileItem fileItem = new FileItem();
					fileItem.file = file[i];
					fileItem.isChecked = false;
					if (action.add(fileItem) && !mStopped) {
						launcher.runOnUiThread(action);
						action = new ChangeNotifier(fileAdapter, false);
					}
				}
			}
			File tmp;
			while (!list.isEmpty()) {
				tmp = list.removeFirst();
				if (tmp.isDirectory()) {
					file = tmp.listFiles();
					if (file == null) {
						continue;
					}
					final int length = file.length;
					for (int i = 0; i < length; i = i + 1) {
						if (file[i].isDirectory()) {
							list.add(file[i]);
						}
						if (file[i].getName().contains(mKeyword)) {
							FileItem fileItem = new FileItem();
							fileItem.file = file[i];
							fileItem.isChecked = false;
							if (action.add(fileItem) && !mStopped) {
								launcher.runOnUiThread(action);
								action = new ChangeNotifier(fileAdapter, false);
							}
						}
					}
				}
			}
			launcher.runOnUiThread(action);
			mRunning = false;
		}
	}

	private boolean mApplicationsLoaded;
	private FileAdapter mFileAdapter;

	synchronized boolean loadFiles(boolean isLaunching,
			FileExplorer fileExplorer, boolean localeChanged, File root,
			String keyword, int mode) {

		if (isLaunching && mApplicationsLoaded && !localeChanged) {
			mFileAdapter = new FileAdapter(fileExplorer, mFiles, mode);
			return false;
		}

		stopAndWaitForApplicationsLoader();

		if (mFileAdapter == null || isLaunching || localeChanged) {
			mFiles = new ArrayList<FileItem>(DEFAULT_LIST_SIZE);
			mFileAdapter = new FileAdapter(fileExplorer, mFiles, mode);
		}

		mApplicationsLoaded = false;

		if (isLaunching) {
			startFileLoader(fileExplorer, root, keyword);
			return false;
		}

		return true;
	}

	private FilesLoader mFilesLoader;
	private Thread fileLoadThread;

	private synchronized void startFileLoader(FileExplorer fileExplorer,
			File root, String keyword) {

		stopAndWaitForApplicationsLoader();

		mFilesLoader = new FilesLoader(fileExplorer, root, keyword);
		fileLoadThread = new Thread(mFilesLoader, "File Loader");
		fileLoadThread.start();
	}

	private synchronized void stopAndWaitForApplicationsLoader() {
		if (mFilesLoader != null && mFilesLoader.isRunning()) {

			mFilesLoader.stop();
			// Wait for the currently running thread to finish, this can take a
			// little
			// time but it should be well below the timeout limit
			try {
				fileLoadThread.join(APPLICATION_NOT_RESPONDING_TIMEOUT);
			} catch (InterruptedException e) {
				// EMpty
			}
		}
	}

	private static final long APPLICATION_NOT_RESPONDING_TIMEOUT = 5000;
	private static final int DEFAULT_LIST_SIZE = 0;

	private static final int BUFFER_SIZE = 10;

	/**
	 * 
	 * @author gjbie
	 *
	 */
	private static class ChangeNotifier implements Runnable {
		private final FileAdapter mFileAdapter;
		private final ArrayList<FileItem> mBuffer;

		private boolean mFirst = true;

		ChangeNotifier(FileAdapter fileAdapter, boolean first) {
			mFileAdapter = fileAdapter;
			mFirst = first;
			mBuffer = new ArrayList<FileItem>(BUFFER_SIZE);
		}

		public void run() {
			FileAdapter fileAdapter = mFileAdapter;
			// Can be set to null on the UI thread by the unbind() method
			if (fileAdapter == null) {
				return;
			}
			if (mFirst) {
				fileAdapter.setNotifyOnChange(false);
				fileAdapter.clear();
				mFirst = false;
			}

			final ArrayList<FileItem> buffer = mBuffer;
			final int count = buffer.size();

			for (int i = 0; i < count; i++) {
				fileAdapter.setNotifyOnChange(false);
				fileAdapter.add(buffer.get(i));
			}
			buffer.clear();
			fileAdapter.setNotifyOnChange(true);
			fileAdapter.notifyDataSetChanged();
		}

		boolean add(FileItem fileItem) {
			final ArrayList<FileItem> buffer = mBuffer;
			buffer.add(fileItem);
			return buffer.size() >= BUFFER_SIZE;
		}
	}

	public final FileAdapter getFilesAdapter() {
		return mFileAdapter;
	}
}
